package com.upc.feedish.ui.user;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.common.collect.BiMap;
import com.upc.feedish.MainActivity;
import com.upc.feedish.R;
import com.upc.feedish.UsermodifyActivity;
import com.upc.feedish.shopp.ShoppingCartActivity;
import com.upc.feedish.utils.DataBaseController;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.sql.Array;

import static android.content.Context.MODE_PRIVATE;

public class UserFragment extends Fragment {
    private ImageView blurImageView;
    private ImageView avatarImageView;
    private com.upc.feedish.item_view stop1;
    private com.upc.feedish.item_view modify;
    private TextView tvUsername;
    SharedPreferences sp;
    //    private HomeViewModel homeViewModel;
//    private FragmentHomeBinding binding;
    private View root;
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        if(root==null){
            root=inflater.inflate(R.layout.fragment_user,container,false);
        }

        sp = getActivity().getSharedPreferences("data",MODE_PRIVATE);
        String localUsername= sp.getString("username","");
        tvUsername=root.findViewById(R.id.user_name);
        tvUsername.setText(localUsername);

        blurImageView = (ImageView) root.findViewById(R.id.iv_blur);
        avatarImageView = (ImageView) root.findViewById(R.id.iv_avatar);
        int icons = R.drawable.head;
        Bitmap profilePhoto =getPic(localUsername);
        if(profilePhoto!=null){
            blurImageView.setImageBitmap(profilePhoto);
            avatarImageView .setImageBitmap(profilePhoto);
        }else {
            blurImageView.setImageResource(icons);
            avatarImageView .setImageResource(icons);
        }

        modify = root.findViewById(R.id.modify);
        modify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), UsermodifyActivity.class);
                startActivityForResult(intent,100);
            }
        });
        stop1 = root.findViewById(R.id.stop);
        stop1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(getActivity()).setTitle("操作提示")//设置对话框标题
                        .setMessage("您确定要退出登录吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                            @Override
                            public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件，点击事件没写，自己添加
                                SharedPreferences.Editor editor = sp.edit();
                                editor.putString("token","");
                                editor.apply();
                                startActivity(new Intent(getActivity(),MainActivity.class));
                                getActivity().finish();
//                                Intent intent = new Intent(getActivity(), MainActivity.class);
//                                startActivity(intent);
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮

                    @Override
                    public void onClick(DialogInterface dialog, int which) {//响应事件，点击事件没写，自己添加

                    }

                }).show();//在按键响应事件中显示此对话框
            }
        });
//            public void onClick(View v) {
//                Intent intent = new Intent(getActivity(), MainActivity.class);
//                startActivity(intent);
//            }
//        });
//        Glide.with(getActivity()).load(R.drawable.head)
//                .bitmapTransform(new BlurTransformation(getActivity(), 25), new CenterCrop(getActivity()))
//                .into(blurImageView);
//        Glide.with(getActivity()).load(R.drawable.head)
//                .bitmapTransform(new CropCircleTransformation(getActivity()))
//                .into(avatarImageView);
        return root;
    }



    public Bitmap getPic(String name)  {
//        savePicOnline(name);
        String filename = name + ".jpg";
        File directory = getActivity().getFilesDir();
        File file = new File(directory, filename);
        InputStream is= null;
        try {
            is = new FileInputStream(file);
            byte[] bytes=new byte[(int) file.length()];
            is.read(bytes);
            return BitmapFactory.decodeByteArray(bytes,0,bytes.length);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }




    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100&&resultCode == 100){
            Bitmap bitmap=getPic(sp.getString("username",""));
            blurImageView.setImageBitmap(bitmap);
            avatarImageView .setImageBitmap(bitmap);
        }
    }




    public void savePicOnline(String name){
        new Thread(new Runnable() {
            @Override
            public void run() {
                DataBaseController dataBaseController=new DataBaseController();
                byte[] bytes=dataBaseController.getFile(sp.getString("token",""),name);
                String filename = name + ".jpg";
                try (FileOutputStream fos = getActivity().openFileOutput(filename, Context.MODE_PRIVATE)) {
                    fos.write(bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

}